<template>
  <!-- 这里是用户权限管理页面 -->
  <div class="auth-container">
    <el-card>
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="role" label="角色" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="modifyTime" label="修改时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-select 
              v-model="row.role" 
              @change="(value) => updateRole(row.userName, value)"
            >
              <el-option label="用户" value="用户" />
              <el-option label="管理员" value="管理员" />
              <el-option label="商家" value="商家" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface User {
  id: number
  userName: string
  role: string
  createTime: string
  modifyTime: string
}

const userList = ref<User[]>([])
// 页面加载完成后，调用finAll，获取用户列表
const fetchUsers = async () => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    const res = await axios.get('/tUsers/findAll', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (res.data.code === 200) {
      userList.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}
//更新用户角色（权限）
const updateRole = async (userName: string, role: string) => {
  try {
    const token = localStorage.getItem('adminToken') || ''
    await axios.get('/tUserInfo/setRegister', {
      params: {
        userName,
        role
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    ElMessage.success('角色更新成功')
    fetchUsers() // 刷新列表
  } catch (error) {
    ElMessage.error('角色更新失败')
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.auth-container {
  padding: 20px;
}
</style>
